import { snapdom } from '@zumer/snapdom';
import type { Ref } from 'vue';
import { ElNotification } from 'element-plus';

// 定义 snapdom.toPng 返回的类型
interface PngResult {
  src: string;
}

export const useDownloadImage = () => {
  // 带重试机制的toPng方法
  const toPngWithRetry = async (element: HTMLElement, options: any, maxRetries = 3, timeout = 10000): Promise<PngResult> => {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        // 添加超时控制
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('toPng timeout')), timeout);
        });

        const toPngPromise = snapdom.toPng(element, options);

        // 使用Promise.race来实现超时控制
        const result = await Promise.race([toPngPromise, timeoutPromise]) as PngResult;

        return result;
      } catch (error) {
        console.warn(`toPng attempt ${attempt} failed:`, error);

        if (attempt === maxRetries) {
          throw error;
        }

        // 等待一段时间后重试
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
      }
    }

    // 这行代码理论上永远不会执行，但为了满足 TypeScript 的要求
    throw new Error('所有重试都失败了');
  };

  const saveAsImage = async (phoneRef: Ref<HTMLElement | null>, currentPage: number | string) => {
    if (!phoneRef.value) return;

    try {
      const scale = 2;

      // 使用带重试机制的toPng方法
      const pngImage = await toPngWithRetry(phoneRef.value, {
        scale: scale,
        embedFonts: true
      });

      // 获取PNG格式的数据URL
      const dataUrl = pngImage.src;

      // 转换为图片并下载
      const link = document.createElement('a');
      const timeStr = +new Date();
      const fileName = `${timeStr}(${String(currentPage).padStart(3, '0')}).png`;
      link.download = fileName;
      link.href = dataUrl;

      // 监听下载完成
      return new Promise<boolean>((resolve, reject) => {
        link.onclick = () => {
          // 显示成功提示
          ElNotification({
            title: '文件保存成功',
            message: `文件名：${fileName}，当前第 ${currentPage} 张`,
            type: 'success',
            duration: 1000,
            position: 'bottom-left'
          });
          resolve(true);
        };

        // 添加错误处理
        link.onerror = () => {
          reject(new Error('下载失败'));
        };

        link.click();
      });
    } catch (error) {
      // 显示错误提示
      ElNotification({
        title: '文件保存失败',
        message: '图片保存失败，已尝试多次重试',
        type: 'error',
        duration: 3000,
        position: 'bottom-left'
      });
      console.error('保存图片失败:', error);
      return false;
    }
  };

  return { saveAsImage };
};